import React from 'react';
import { List, Spin } from 'antd';
import styles from './TableList.less';

import TableListItem from './TableListItem';


class TableList extends React.Component {

  basePagination = {
    onChange: (current, pageSize) => {
      this.handlePageChage(current, pageSize, 'page')
    },
    onShowSizeChange: (current, pageSize) => {
      this.handlePageChage(current, pageSize, 'size');
    },
  }

  /* 页数或页码改变的回调 */
  handlePageChage = (current, pageSize, type = 'page') => {
    const { onPageChange, pagination = {} } = this.props;
    const { onChange, onShowSizeChange } = pagination || {};
    const newCurrent = type === 'size' ? 1 : current; // pageSize改变，页数变为1
    if (onPageChange) onPageChange(newCurrent, pageSize);
    if (type === 'page' && onChange) {
      onChange(newCurrent, pageSize);
    } else if (type === 'size' && onChange) {
      onShowSizeChange(newCurrent, pageSize);
    }
  }

  render() {
    const {
      dataSource = [],
      columns = [],
      titleName,
      operationName,
      pagination = false,
      loading = false,
      rowKey,
      className = '',
    } = this.props;
    const hideOnSinglePage = !(dataSource.length > 0);
    const newPagination = pagination ? { ...pagination, ...this.basePagination, hideOnSinglePage } : pagination;
    const subColumns = columns.filter(citem => { return citem.dataIndex !== titleName && citem.dataIndex !== operationName });
    const rightColumns = columns.filter(citem => citem.dataIndex === operationName);
    const titleColumns = columns.filter(citem => citem.dataIndex === titleName);
    const baseColWidth = 100 / subColumns.length - subColumns.length;
    return (
      <div className={`${styles.tablecon} ${className}`}>
        <Spin spinning={loading}>
          <List
            itemLayout="vertical"
            size="large"
            pagination={newPagination}
            dataSource={dataSource}
            style={{ minHeight: window.innerHeight - 64 - 16 - 16-16 - 48 - 80 - 104}}
            renderItem={item => {
              const itemkey = rowKey instanceof Function ? rowKey(item) : rowKey;
              const key = item[itemkey] || itemkey;
              return (
                <List.Item
                  key={key}
                >
                  <div className={styles.listContent}>
                    <TableListItem
                      item={item}
                      columns={subColumns}
                      rightColumns={rightColumns}
                      titleColumns={titleColumns}
                      titleName={titleName}
                      baseColWidth={baseColWidth}
                    />
                  </div>
                </List.Item>
              )
            }}
          />
        </Spin>
      </div>
    );
  }
}
export default TableList;